<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="成员姓名" prop="relativeName">
        <el-input
          v-model="queryParams.relativeName"
          placeholder="请输入成员姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="关系类型" prop="relationType">
        <el-select
          v-model="queryParams.relationType"
          placeholder="请选择关系类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.FAMILY_RELATIONSHIP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm"
          v-hasPermi="['family:relationships:add']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增关系
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="关系人" align="center" prop="relativeName" />
      <el-table-column label="关系类型" align="center" prop="relationType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.FAMILY_RELATIONSHIP_TYPE" :value="scope.row.relationType" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180" />
      <el-table-column label="操作" align="center" width="160">
        <template #default="scope">
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['family:relationships:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 新增关系弹窗 -->
  <el-dialog
    :title="'新增关系'"
    v-model="dialogVisible"
    width="500px"
    append-to-body
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="关系类型" prop="relationType">
        <el-select
          v-model="formData.relationType"
          placeholder="请选择关系类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.FAMILY_RELATIONSHIP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关系人" prop="relativeId">
        <el-select
          v-model="formData.relativeId"
          placeholder="请选择关系人"
          clearable
          class="!w-240px"
          filterable
          remote
          :remote-method="handleSearch"
          :loading="searchLoading"
        >
          <el-option
            v-for="item in memberOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { RelationshipsApi, RelationshipsSaveReqVO } from '@/api/family/relationships'
import { MembersApi } from '@/api/family/members'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 家族关系 列表 */
defineOptions({ name: 'Relationships' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  memberId: undefined as number | undefined,
  relativeName: undefined as string | undefined,
  relationType: undefined as number | undefined,
  pageNo: 1,
  pageSize: 10
})
const queryFormRef = ref() // 搜索的表单

// 表单相关
const dialogVisible = ref(false)
const formRef = ref()
const formData = ref<RelationshipsSaveReqVO>({
  memberId: undefined as unknown as number,
  relationType: undefined as unknown as number,
  relativeId: undefined as unknown as number
})
const formRules = {
  relationType: [{ required: true, message: '请选择关系类型', trigger: 'change' }],
  relativeId: [{ required: true, message: '请选择关系人', trigger: 'change' }]
}

// 成员搜索相关
const searchLoading = ref(false)
const memberOptions = ref<Array<{id: number, name: string}>>([])

/** 查询列表 */
const getList = async () => {
  if (!props.memberId) return
  loading.value = true
  try {
    const data = await RelationshipsApi.getRelationshipsByMemberId({
      memberId: Number(props.memberId),
      relativeName: queryParams.relativeName || undefined,
      relationType: queryParams.relationType || undefined
    })
    list.value = data
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 搜索成员 */
const handleSearch = async (query: string) => {
  if (query) {
    searchLoading.value = true
    try {
      const data = await MembersApi.getMembersPage({
        pageNo: 1,
        pageSize: 10,
        name: query
      })
      memberOptions.value = data.list.filter(item => item.id !== props.memberId)
    } finally {
      searchLoading.value = false
    }
  } else {
    memberOptions.value = []
  }
}

/** 打开表单弹窗 */
const openForm = () => {
  dialogVisible.value = true
  formData.value = {
    memberId: Number(props.memberId),
    relationType: undefined as unknown as number,
    relativeId: undefined as unknown as number
  }
  memberOptions.value = []
}

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  try {
    console.log('提交表单数据:', formData.value)
    await RelationshipsApi.createRelationships(formData.value)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    await getList()
  } catch (error) {
    console.error('新增关系失败:', error)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await RelationshipsApi.deleteRelationships(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch (error) {
    console.error('删除关系失败:', error)
  }
}

/** 初始化 */
onMounted(() => {
  getList()
})

/** 监听成员ID变化 */
const props = defineProps({
  memberId: {
    type: [String, Number],
    required: true
  }
})

watch(() => props.memberId, () => {
  getList()
}, { immediate: true })
</script> 
